﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SSN.DotNet;
using SSN.WebFramework;
using System.Web.UI.WebControls;

namespace SSN.WebFramework.Controls
{
    ///TODO: Include options for:
    /// -Any rep
    /// -My supervisted reps

    /// <summary>
    /// Automatically fills in a drop down list with all the linked in reps for a user.
    /// </summary>

    public class RepDropDownList : System.Web.UI.WebControls.DropDownList, IBindable
    {
        /// <summary>
        /// Includes an option for "All Reps" with all rep numbers in a comma delimited string.
        /// </summary>
        public bool IncludeAnyRep { get; set; }

        /// <summary>
        /// Fills in the item list with reps and automatically selects the "favorite rep".
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
		   AuthPage page = (AuthPage)Page;
		   foreach(LinkedRep rep in page.UserManager.LinkedReps) {
			   Items.Add(new ListItem(rep.ToString(),rep.RepNumber));
		   }
		   if(IncludeAnyRep) {
			   Items.Insert(0,new ListItem("Any Rep",page.UserManager.LinkedRepNumbers.ToDelimitedString(" ")));
		   }

		   if(!page.IsPostBack) {
			   string selectedRep = page.SecurityManager.CurrentUser.GetUserProperty("fwfavrepno");
			   if(!String.IsNullOrEmpty(selectedRep)) {
				   SelectedValue = selectedRep;
			   }
		   }

		   base.OnInit(e);
        }

	   public string BindProperty { get; set; }

        public void BindFromObject( object obj ) {
		   PropertyInfo info=obj.GetType().GetProperty(BindProperty);
		   if(info!=null) {
			   object v = info.GetValue(obj,null);
			   if(v != null) {
				   this.SelectedValue = v.ToString();
			   }
		   }
        }

        public string BindTranslator { get; set; }

	   public void BindToObject(object obj) {
		   PropertyInfo info=obj.GetType().GetProperty(BindProperty);
		   if(info!=null) {
			   info.SetValue(obj,Convert.ChangeType(this.SelectedValue,info.PropertyType),null);
		   }
	   }
    }
}
